package com.eight.cloud.message.listener;

import com.eight.cloud.openfeign.message.model.vo.MqTestVo;
import com.eight.cloud.rabbitmq.util.MessageUtils;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.io.IOException;
import java.util.function.Consumer;

/**
 * @ClassName: MqListener
 * @Author: TXC
 * @Date: 2025-08-13 17:39
 **/
@Slf4j
@Component
public class MqListener {

    /**
     * 订阅websocket队列（函数名必须和rabbitMq中配置的exchange名称一致）
     * @return 消息消费者
     */
    @Bean
    Consumer<Message<MqTestVo>> websocketConsumer() {
        log.info("初始化订阅");
        return obj -> {
            MqTestVo payload = obj.getPayload();
            Channel channel = MessageUtils.getChannel(obj);
            Long deliveryTag = MessageUtils.getDeliveryTag(obj);
            try {
                Assert.notNull(channel, "channel不能为空");
                Assert.notNull(deliveryTag, "deliveryTag不能为空");
                channel.basicAck(deliveryTag, false);
            } catch (IOException e) {
                log.error("消息接收失败：{}", payload, e);
                throw new RuntimeException(e);
            }
            log.info("消息接收成功：{}", payload);
        };
    }
}
